const Koa = require("koa");
const app = new Koa();
const json = require("koa-json");
const onerror = require("koa-onerror");
const bodyparser = require("koa-bodyparser");
const logger = require("koa-logger");
const { initRouter } = require("./routes");
const { initModels } = require("./db");
const { httpLog } = require("./utils/logger");

onerror(app);
app.use(bodyparser());
app.use(json());
app.use(
  logger((str, args) => {
    httpLog.info(args.slice(1).join(" "));
  })
);
app.use(require("koa-static")(__dirname + "/public"));

initModels()
  .then(() => {
    console.log("数据库启动成功");
  })
  .catch((err) => {
    console.error("数据库启动失败");
  });

initRouter(app);

app.on("error", (err, ctx) => {
  console.error("server error", err, ctx);
});

module.exports = app;
